package com.baomidou.springmvc.common.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.springmvc.core.user.model.User;
import com.baomidou.springmvc.core.user.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;

/**
 * Shiro 认证
 * Created by chenkai on 2017/4/27.
 */
public class ShiroRealm extends AuthorizingRealm {
    @Autowired
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) getAvailablePrincipal(principalCollection);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.setEntity(new User());
        userEntityWrapper.like("name", username);
        //   User user = userService.selectOne(userEntityWrapper);
        Set<String> role = new HashSet<>(); //角色
        role.add("admin");
        info.setRoles(role);

//        Set<String> s = new HashSet<>();
//        s.add("printer:print");
//        s.add("printer:query");
//        info.setStringPermissions(s);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        String password = new String((char[]) authenticationToken.getCredentials());
           User user = userService.selectOne(new EntityWrapper<User>().eq("name", username).eq("age", password));

        //账号不存在
        if(user == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }

        //密码错误
        if(!password.equals(user.getAge().toString())) {
            throw new IncorrectCredentialsException("账号或密码不正确");
        }
//
//        //账号锁定
//        if(user.getStatus() == 0){
//            throw new LockedAccountException("账号已被锁定,请联系管理员");
//        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        return info;
    }
}
